package cores

import (
	"bytes"
	"encoding/json"
	"fmt"
	log "github.com/sirupsen/logrus"
	"net/http"
	"simulationFulu/dao"
	"simulationFulu/models"
	"simulationFulu/utils"
	"strconv"
	"time"
)

// 下单请求
func CardOrder(bizContent string) string {
	//解析对象
	var req models.InputCardOrderReq
	err := json.Unmarshal([]byte(bizContent), &req)
	if err != nil {
		log.Error(err)
	}
	product := dao.Get(req.ProductId)
	if product == nil {
		panic("找不到对应产品" + strconv.Itoa(req.ProductId))
	}
	order := CreateOrder(product, req.BuyNum, req.CustomerOrderNo)

	// 组装回调
	cbReq := &models.CallbackReq{}
	cbReq.CustomerOrderNo = order.CustomerOrderNo
	cbReq.ProductId = order.ProductId
	cbReq.BuyNum = order.BuyNum
	cbReq.OperatorSerialNumber = order.OperatorSerialNumber
	cbReq.OrderId = order.OrderId
	cbReq.ChargeFinishTime = order.FinishTime
	cbReq.OrderStatus = order.OrderState
	cbReq.Price = product.ProductPrice
	cbReq.RechargeDescription = ""
	secret := models.GetConfig().Secret
	log.Info("Secret:", secret)
	cbReq.Sign = utils.BuildFuluMd5Sign(cbReq, secret)
	// 序列化返回值
	cbjson, cber := json.Marshal(cbReq)
	if cber == nil {
		log.Error(cber)
	}

	defer func() {
		// 启动线程
		go callback(cbjson)
		log.Info("defer callback is done")
	}()

	// 组装结果
	var res models.OutputCardOrderRes
	res.CustomerOrderNo = order.CustomerOrderNo
	res.ProductId = order.ProductId
	res.BuyNum = order.BuyNum
	res.OrderType = order.OrderType //直充
	//  计算总价值
	res.OrderPrice = order.OrderPrice
	res.OrderId = order.OrderId
	res.CreateTime = order.CreateTime
	//res.CreateTime=time.Now().Format("yyyyMMdd HH:mm:ss")
	res.ProductName = order.ProductName
	res.OrderState = order.OrderState
	res.OperatorSerialNumber = order.OperatorSerialNumber
	// 序列化返回值
	b, er := json.Marshal(res)
	if er == nil {
		log.Error(err)
	}
	return string(b)
}

// 订单查询
func CardOrderQuery(bizContent string) string {
	// 解析对象
	var req models.InputOrderGet
	err := json.Unmarshal([]byte(bizContent), &req)
	if err != nil {
		log.Error(err)
	}
	// 组装结果
	res := OrderQueryByCustomerNo(req.CustomerOrderNo)
	// 序列化返回值
	b, er := json.Marshal(res)
	if er == nil {
		log.Error(err)
	}
	return string(b)
}

//回调
func callback(data []byte) {
	//  处理异常的函数
	defer func() {
		fmt.Println("开始处理异常")
		// 获取异常信息
		if err := recover(); err != nil {
			//  输出异常信息
			fmt.Println("error:", err)
		}
		fmt.Println("结束异常处理")
	}()

	time.Sleep(time.Second * 30)
	log.Info("DelayJob is running")

	// 请求回调
	url := models.GetConfig().CallBackUrl
	log.Info("当前CallBackUrl:", url)
	if len(url) > 0 {
		client := &http.Client{}
		req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
		//req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36")
		req.Header.Set("Content-Type", "application/json")
		res, err := client.Do(req)
		if err != nil {
			// 错误处理
			log.Fatal(err)
		}
		if res.StatusCode != 200 {
			log.Fatalf("status code error: %d %s", res.StatusCode, res.Status)
		}

	} else {
		log.Info("Url is nil")
	}
}
